from venv import create
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import time
import os
from pdf_process import download_states

from pdf_process import pdfreference, get_page_txt, get_ref_list, get_ref_pages, convert_reflist_to_class
class Table(QWidget):
    '''
    creat a table widget to show the information of references
    '''
    def __init__(self, arg=None):
        super(Table, self).__init__(arg)
        self.model = QStandardItemModel(1, 4)
        self.model.setHorizontalHeaderLabels(['title', 'author', 'date', 'states'])

        self.tableView = QTableView()
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.tableView.setSortingEnabled(True)

        dlgLayout = QVBoxLayout()
        dlgLayout.addWidget(self.tableView)
        self.setLayout(dlgLayout)

        self.refdata = []
        return

    def export_ref_data(self, references):
        self.refdata = references
        num = len(references)
        # self.btn = [i for i in range(num)]
        for row,ref_class in enumerate(self.refdata):
            # if ref_class.content["title"] != '':
            title = QStandardItem(ref_class.content["title"])
            author_temp = ",".join(ref_class.content["author"])
            author = QStandardItem(author_temp)
            date = QStandardItem(ref_class.content["date"])
            state = QStandardItem(str(ref_class.states))
            ref_class.btn = []
            ref_class.btn = QPushButton("creat")
            # element = QPushButton("test")
            # self.tableView.setCellWidget(row, 3, self.refdata)
            # print(row)
            self.model.setItem(row, 0, title)
            self.model.setItem(row, 1, author)
            self.model.setItem(row, 2, date)
            self.model.setItem(row, 3, state)
            self.tableView.setIndexWidget(self.model.index(row,3), ref_class.btn)
            self.element_download_state(ref_class)
            # self.btn[row] = QPushButton("sss")
            # my_btn.setProperty('1',column)
            # self.tableView.setIndexWidget(self.model.index(row,3), self.btn[row])
        # print(self.refdata)
        return

    def element_download_state(self, element):
        if element.content["title"] != "":
            path = os.getcwd() + '\\bib\\'+element.content["title"] + ".bib"
            
            # print(path)
            # print(os.path.exists(path))
            if os.path.exists(path):
                element.states = download_states.download_success
        # print(element.btn)



        # self.model.setItem(QStandardItem(str(element.states)))
        if element.states == download_states.not_found:
            element.btn.setText("not found")
            element.btn.setEnabled(False)
        elif element.states == download_states.not_download:
            element.btn.setText("download")
            # if element.btn.sign
            try:element.btn.disconnect()
            except Exception:pass
            element.btn.clicked.connect(element.downloadbib)
        elif element.states == download_states.download_success:
            element.btn.setText("open bib")
            try:element.btn.disconnect()
            except Exception:pass
            element.btn.clicked.connect(element.openbib)
        elif element.states == download_states.waiting:
            element.btn.setText("processing,click again")

    def download_state(self):
        if self.refdata != []:
            for element in self.refdata:
               
                self.element_download_state(element)
        return

class TimerMessageBox(QMessageBox):
    def __init__(self, timeout=3, auto=True, parent=None):
        super(TimerMessageBox, self).__init__(parent)
        self.setWindowTitle("download message")
        self.time_to_wait = timeout
        self.auto = auto
        self.setText("waiting")
        self.setStandardButtons(QMessageBox.NoButton)
        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.changeContent)
        self.timer.start(timeout)
        # self.boxthread = Update_state()

    def changeContent(self):
        # self.setText("wait (closing automatically in %d secondes.)" %(self.time_to_wait))
        self.time_to_wait -= 1
        if self.time_to_wait <= 0:
            self.timer.stop()
            if self.auto:
                self.accept()
                self.close()

    # def closeEvent(self, event):
    #     self.timer.stop()
    #     event.accept()
    
class Update_state(QThread):
    '''
    creat a thread to update the states of downloading of references
    '''
    update_date = pyqtSignal(str)
    def __init__(self, *args, **kwargs):
        super(Update_state,self).__init__(*args, **kwargs)

        # to control the whether the QThread emit signal
        self._isPause = False
    def run(self):
        '''
        send a signal at regular intervals
        '''
        cnt = 0
        while True:
            if self._isPause:
                break
            cnt += 1
            self.update_date.emit(str(cnt))
            if cnt >= 1000:
                cnt = 0
            # self.update_date.emit(str(cnt))
            print("updates")
            time.sleep(1)

class mainwindow(QMainWindow):
    '''
    creat a window as the main part of the visual interface,
    include the menubar, status menu, Table
    '''

    sig = pyqtSignal(int)
    def __init__(self):
        super().__init__()

        self.initUI()



    def initUI(self):      
        self.resize(1000,800)
        self.setWindowTitle('PDF References Download')

        # self.textEdit = QTextEdit()
        # self.setCentralWidget(self.textEdit)
        self.statusBar()

        openFile = QAction('Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.showDialog)

        downloadall = QAction('download all',self)
        downloadall.setShortcut('Ctrl+D')
        downloadall.setStatusTip('Download all bib files of references')
        downloadall.triggered.connect(self.download_all)

        noorder = QAction('resorting',self)
        noorder.setShortcut('Ctrl+L')
        noorder.setStatusTip('Restore the original order')
        noorder.triggered.connect(self.noorder)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)
        downloadMenu = menubar.addMenu('download all')
        downloadMenu.addAction(downloadall)
        menubar.addMenu('resorting').addAction(noorder)


        self.table = Table()
        v_layerout = QVBoxLayout()
        v_layerout.addWidget(self.table)

        widget = QWidget()
        widget.setLayout(v_layerout)
        self.setCentralWidget(widget)

        # self.show()


    def showDialog(self):

        fname = QFileDialog.getOpenFileName(self, 'Open file', './')

        if fname[0]:
            print(fname)
            print(fname[0])
            if fname[0][-4:] == ".pdf":
                pdf_path = fname[0]
                ref_info = get_ref_pages(pdf_path)
                ref_list = get_ref_list(ref_info)
                references = convert_reflist_to_class(ref_list)
                self.table.export_ref_data(references)
                self.create_thread()
            else:
                self.mesbox = QMessageBox.warning(self,  "warning", "it is not a pdf format file",QMessageBox.Cancel)
        return

    def create_thread(self):
        update_data_thread = Update_state()
        self.update_thread = update_data_thread
        self.update_thread.update_date.connect(lambda: ex.table.download_state())
        update_data_thread.start()

    def download_all(self):
        for element in self.table.refdata:
            element.downloadbib()
            self.download_message_box()
        return

    def download_message_box(self):
        self.messagebox = TimerMessageBox()
        # self.messagebox.show()
        self.messagebox.exec_()
        return
    def noorder(self):
        self.table.model.removeRows(0, self.table.model.rowCount())
        self.table.show()
        i=0
        self.update_thread._isPause = True
        # self.table.export_ref_data(self.table.refdata)
        for row,ref_class in enumerate(self.table.refdata):
            # if ref_class.content["title"] != '':
            title = QStandardItem(ref_class.content["title"])
            author_temp = ",".join(ref_class.content["author"])
            author = QStandardItem(author_temp)
            date = QStandardItem(ref_class.content["date"])
            state = QStandardItem(str(ref_class.states))
            # ref_class.btn.deleteLater()
            # print(ref_class.btn)
            ref_class.btn = QPushButton("creat")
            # print(ref_class.btn.isSignalConnected(ref_class.downloadbib))
            # print(ref_class.btn)
            i = i + 1
            self.table.model.setItem(row, 0, title)
            self.table.model.setItem(row, 1, author)
            self.table.model.setItem(row, 2, date)
            self.table.model.setItem(row, 3, state)
            self.table.tableView.setIndexWidget(self.table.model.index(row,3), ref_class.btn)
            print(self.table.model.index(row,2).data())
            self.table.element_download_state(ref_class)
        self.update_thread._isPause = False
        return

    # def test(self):
    #     self.sig.emit(self.table.refdata[0].downloadbib)
    #     self.sig.connect(self.test_print)
    #     return
    # def test_print(self):
    #     print("test success")

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = mainwindow()
    ex.show()
    sys.exit(app.exec_())